export default defineEventHandler(async (event) => {
  const headers = getHeaders(event)
  // console.log('user-id:', headers['user-id'], 'role-id:', headers['role-id'], 'company-id:', headers['company-id'])

  const api_method = event.method
  const reqUrl = getRequestURL(event)
  const api_path = reqUrl.pathname.replace('/api/s', '')
  let reqData: any = {}
  if (api_method.toUpperCase() === 'GET') {
    const qs = getQuery(event)
    if (isNotNilOrEmpty(qs)) {
      reqData = qs
    }
  } else {
    const _body = await readBody(event)
    if (isNotNilOrEmpty(_body)) {
      reqData = _body
    }
  }
  if (isNotNilOrEmpty(reqData) && type(reqData) === 'String') {
    setResponseStatus(event, 203)
    return { code: 203, msg: '参数不能是 string !' }
  }
  const limit = Number(reqData?.limit) || 50
  const offset = Number(reqData?.offset) || 0

  const apiList: any = await knex.select('id', 'define', 'to_path').from('dict_api')
    .where('api_method', api_method.toUpperCase())
    .whereNull('deleted_at')
    .where('api_path', api_path)

  if (isNilOrEmpty(apiList) || isNilOrEmpty(apiList[0].define)) {
    setResponseStatus(event, 203)
    return { code: 203, msg: 'api接口不存在，请添加接口！', result: api_path }
  } else if (apiList.length > 1) {
    setResponseStatus(event, 203)
    return { code: 203, msg: 'api接口重复定义，请删除重复项！', result: api_path }
  }
  const dict_api = apiList[0]
  const colConfig = dict_api.define

  if (!['/get', '/post', '/put', '/patch', '/delete'].includes(dict_api.to_path)) {
    setResponseStatus(event, 203)
    return { code: 203, msg: '目标路径不规范!', result: { 'to_path规范值': ['/get', '/post', '/put', '/patch', '/delete'] } }
  }
  // 新增或修改
  if (['/put', '/patch'].includes(dict_api.to_path)) {
    if (isNilOrEmpty(headers['user-id'])) {
      setResponseStatus(event, 401)
      return { code: 401, msg: '请登录!' }
    }
    if (isNilOrEmpty(reqData)) {
      setResponseStatus(event, 203)
      return { code: 203, msg: '待更新数据为空!' }
    }
    const table = dict_api.define[0].table_id
    const formData = getUpsertData({ reqData, colConfig, userId: headers['user-id'] })
    const result = await upsertRows(table, formData, headers['user-id'])
    if (result.code !== 0) {
      setResponseStatus(event, result.code)
    }
    return result
  }
  // 删除
  if (dict_api.to_path === '/delete') {
    if (isNilOrEmpty(headers['user-id'])) {
      setResponseStatus(event, 401)
      return { code: 401, msg: '请登录!' }
    }
    const table = dict_api.define[0].table_id
    let error
    if (reqData.force) {
      error = await deleteRowHard(table, reqData.id)
    } else {
      error = await deleteRow(table, reqData.id, headers['user-id'])
    }
    if (isNotNilOrEmpty(error)) {
      setResponseStatus(event, 203)
      return { code: 203, msg: '删除失败!', result: error.toString() }
    }
    return { code: 0, msg: 'success', result: reqData.force ? '数据删除成功！' : '标记为删除成功！' }
  }
  // 查询
  if (needLogin(colConfig) && isNilOrEmpty(headers['user-id'])) {
    setResponseStatus(event, 401)
    return { code: 401, msg: '请登录!' }
  }
  // 接口缓存(redis)
  const timestamp = headers.timestamp || ''
  const attributeCode = event.context.attributeCode
  if (isNilOrEmpty(timestamp) && limit < 501) {
    const redis = await getRedisCache()
    const cacheData = await redis.json.get(attributeCode)
    if (isNotNilOrEmpty(cacheData)) {
      // await redis.del(attributeCode)
      return cacheData
    }
  }
  // 将字段参数和分页参数分离开来。
  let reqJson: any = {}
  if (isNotNilOrEmpty(reqData) && !has(reqData, 'colSearch')) {
    const colConfigKeys = ['limit', 'offset']
    Object.keys(reqData).forEach(e => {
      if (!colConfigKeys.includes(e) && isNotNilOrEmpty(reqData[e])) {
        reqJson[e] = reqData[e]
      }
    })
  }

  const tableCols = getTableCols(colConfig)
  try {
    const { sql, countSql, subQueryClean } = genSql({ reqJson, colConfig, tableCols, userId: headers['user-id'], limit, offset })

    const count = await knex.raw(countSql)
    const resp = await knex.raw(sql)
    const dataList = resp[0]
    if (isNotNilOrEmpty(subQueryClean)) {
      const subQueryArr = subQueryClean.split('.')
      dataList.forEach(e => {
        if (isNilOrEmpty(e[subQueryArr[0]][0][subQueryArr[1]])) {
          e[subQueryArr[0]] = []
        }
      })
    }
    const respData = {
      code: 0,
      msg: 'success',
      result: { dataList, total: count[0][0].count, limit, offset },
    }
    // 接口缓存
    if (isNilOrEmpty(timestamp) && limit < 501) {
      const redis = await getRedisCache()
      await redis.json.set(attributeCode, '$', respData)
      const expire = Number(process.env.REDIS_CACHE_EX) || 60
      await redis.expire(attributeCode, expire)
    }
    return respData
  } catch (error) {
    console.log(error)
    setResponseStatus(event, 500)
    return { code: 500, msg: '数据查询失败，请稍后重试。', result: error?.toString() }
  }
})
